package capricornus.scene.preload
{
	import capricornus.components.label.Label;
	import capricornus.core.StageManager;
	import capricornus.events.ResLoaderEvent;
	import capricornus.events.StageEvent;
	import capricornus.net.NetWorkManager;
	import capricornus.net.Path;
	import capricornus.net.loader.ResLoader;
	import capricornus.scene.AbstractScene;
	
	import flash.display.Bitmap;
	import flash.display.Shape;
	import flash.events.Event;
	import flash.events.EventDispatcher;

	[Event(name="scenePreloadComplete", type="capricornus.scene.preload.ScenePreLoadEvent")]
	public class ScenePreLoadController extends EventDispatcher
	{
		private var _scene:AbstractScene;
		
		private var _back:Shape;
		private var _loader:ResLoader;
		private var _label:Label;
		
		private var _bmPreview:Bitmap;
		
		public function ScenePreLoadController( scene:AbstractScene )
		{
			_scene = scene;
			init();
		}
		
		private function init():void
		{
			_back = new Shape();
			_back.graphics.beginFill(0);
			_back.graphics.drawRect( 0, 0, 1, 1 );
			_back.graphics.endFill();
			
			_label = new Label();
			
			_loader = new ResLoader(true);
			_loader.addEventListener( ResLoaderEvent.PROGRESS, onResProgress, false, 0, true );
			_loader.addEventListener( ResLoaderEvent.COMPLETE, onResLoaded, false, 0, true );
		}
		
		public function start( id:String ):void
		{
			_scene.visible = false;
			_label.text = "0%"
			StageManager.stage.addChild( _back );
			StageManager.stage.addChild( _label );
			onResize(null);
			
			_loader.load( Path.getScenePreloadImagePath( id ), NetWorkManager.instance.loaderContext );
			StageManager.instance.addEventListener( StageEvent.RESIZE, onResize, false, 0, true );
		}
		
		public function get bmPreview():Bitmap
		{
			return _bmPreview;
		}
		
		private function onResProgress( e:ResLoaderEvent ):void
		{
			var rate:Number = e.data as Number;
			
			_label.text = int(rate * 100) + "%";
		}
		
		private function onResLoaded( e:Event ):void
		{
			if( _bmPreview != null )
			{
				_bmPreview.bitmapData.dispose();
				_bmPreview.bitmapData = null;
			}
			_bmPreview = _loader.data;
			_scene.visible = true;
			StageManager.stage.removeChild( _back );
			dispatchEvent( new ScenePreLoadEvent( ScenePreLoadEvent.SCENE_PRELOAD_COMPLETE, _bmPreview.bitmapData ) );
		}
		
		private function onResize( e:Event ):void
		{
			_label.x = int((StageManager.stageWidth - _label.width)/2);
			_label.y = int((StageManager.stageWidth - _label.height)/2);
			
			_back.width = StageManager.stageWidth;
			_back.height = StageManager.stageHeight;
		}
	}
}















